package com.nny.alarm.eidt;

import java.util.Calendar;

import android.content.Context;
import android.view.View;

import com.nny.alarm.audio.RingPlayer;
import com.nny.alarm.more.AlarmBriefUtil;
import com.nny.alarm.view.DialTimeView;
import com.nny.alarm.view.DialTimeView.OnDialClickListener;
import com.nny.alarm.view.DialTimeView.OnDialMarkListener;
import com.nny.alarm.view.DigitalTimeView;
import com.uxwine.alarm.Alarm;
import com.uxwine.alarm.TimeRecord;
import com.uxwine.alarm.mon.AlarmContext;
import com.uxwine.alarm.mon.AlarmUtil;
import com.uxwine.alarm.mon.RingManager;
import com.uxwine.util.UxToast;

public class AlarmEditor implements OnDialClickListener, OnDialMarkListener
{
	Context mCtx;
	Alarm mAlarm, mBkAlarm;
	DigitalTimeView mDigital;
	DialTimeView mDial;
	RingPlayer mRing;
	IAlarmEditor[] mEditors;
	
	int mnStep = 0;
	
	public static final int STEP_CYCLE 	= 0;
	public static final int STEP_TIME	= 1;
	public static final int STEP_RING	= 2;
	
	public AlarmEditor(Context ctx)
	{
		mCtx = ctx;
		mRing = new RingPlayer(ctx);
		mEditors = new IAlarmEditor[3];
		mEditors[STEP_CYCLE] = new CycleEditor(this);
		mEditors[STEP_TIME] = new TimeEditor(this);
		mEditors[STEP_RING] = new RingEditor(this);
	}
	
	public void init(DigitalTimeView dttv, DialTimeView dtv)
	{
		mDigital = dttv;
		mDial = dtv;
		mDial.setOnDialClickListener(this);
		mDial.setOnDialMarkListener(this);
	}
	
	public void eidtor(Alarm alarm)
	{
		if(alarm == null)
			create();
		else
			mAlarm = alarm;
		
		mBkAlarm = new Alarm();
		mBkAlarm.copy(mAlarm);
		
		step(STEP_CYCLE);
	}
	
	public void save()
	{
		Alarm a = new Alarm();
		mAlarm.enabled = true;
		mAlarm.trigger = 0;
		if(mAlarm.cycle.isOnce())
		{
			final TimeRecord t = mAlarm.time;
			Calendar c = Calendar.getInstance();
			c.set(t.get(TimeRecord.YEAR), 
					t.get(TimeRecord.MONTH),
					t.get(TimeRecord.DATE), 
					t.get(TimeRecord.HOUR), 
					t.get(TimeRecord.MINUTE));
	        c.set(Calendar.SECOND, 0);
	        c.set(Calendar.MILLISECOND, 0);
			mAlarm.trigger = c.getTimeInMillis();
		}
		if(mAlarm.alert == null)
			mAlarm.alert = RingManager.getDefaultRing();
		
		a.copy(mAlarm);
		long time = -1;
		if(a.id == -1)
		{
			mAlarm.label = "新建闹钟";
			time = AlarmUtil.addAlarm(mCtx, a);
			mAlarm.id = a.id;
		}
		else
		{
			time = AlarmUtil.setAlarm(mCtx, a);
		}
		Calendar c = Calendar.getInstance();
		c.setTimeInMillis(time);
		
		UxToast.sshow(mCtx, "下次闹钟时间：" + AlarmContext.formatDHM(mCtx, c));
	}
	
	public void create()
	{
		mAlarm = new Alarm();
	}
	
	public void step(int step)
	{
		mnStep = step;
		mEditors[step].edit();
	}

	@Override
	public void onClick(View v)
	{
		if(!mEditors[mnStep].next())
			UxToast.sshow(mCtx, "over!!!");
	}

	@Override
	public void onMarkChanged(int index)
	{
		mEditors[mnStep].onMarkChange(index);
	}

	@Override
	public void onMarked(int index)
	{
		mEditors[mnStep].onMarked(index);
	}
	
	public void over()
	{
		mEditors[mnStep].over();
	}
}
